package com.lisp.springframework.web.controller;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lisp.springframework.util.BindResultUtil;


@Controller
public class ModelAndValidateController {

    @RequestMapping("/testModel")
    @ResponseBody
    public String testModel(@ModelAttribute People people) { // @ModelAttribute是默认注解，可以省略
        // 测试URL: http://localhost:8080/springframework/testModel?name=lisp&age=3
        return people.toString();
    }
    
    @RequestMapping(value = "/testModelValidate", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testModelValidate(@Valid People people, BindingResult bindingResult) { // 这里省略了@ModelAttribute
        if(bindingResult.hasErrors()) {
            return BindResultUtil.joinedDefaultMessages(bindingResult);
        }
        return people.toString();
    }
    
    public static class People {
        
        @NotNull(message = "姓名不能为空")
        @Size(max = 50, message = "姓名不能超过50个字符")
        private String name;
        
        @NotNull(message = "年龄不能为空")
        @Max(value = 120, message = "年龄必须小于等于120")
        @Min(value = 0, message = "年龄必须大于等于0")
        private Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "People [name=" + name + ", age=" + age + "]";
        }
    }
}
